/*
 * tests.c
 *
 *  Created on: 2012-8-26
 *      Author: dietoad
 */

#ifndef TESTS_C_
#define TESTS_C_
#include "tests.h"
#include "stdio.h"
#include "stdlib.h"
#include "strings.h"
#include "string.h"
#include  "assert.h"
typedef struct client_socket_t
{
socket_fd client;
sockaddr addr;
u32       client_flag;
}client_t;

//HANDLE event;

thread_ret_t THREAD_API
thread_func(lpvoid lpv)
{
    printf("%s", __FUNCTION__);
    return 0;
}

thread_ret_t THREAD_API
thread_per_client(lpvoid lpv)
{
    u8 loop=1;
    u8 buffer[1024]={0};
    client_t *client=(client_t*)lpv;
    assert(client);

    while(loop==1)
    {

      memset(buffer,0,1024);
      recv(client->client,buffer,1024,0);
//      mcf_error("%s\n",buffer);
//      send(client->client,buffer,1024,0);
      if(strncmp((const char*)buffer,"exit",4)==0)
      {
          close(client->client);
          loop=0;
      }
//      mcf_error("client");
//
//      loop=0;
    }

    if(client)free(client);
    return 0;
}
thread_ret_t THREAD_API
server(lpvoid lpv)
{
    socket_t *server_t;
    assert(lpv!=NULL);
    server_t = (socket_t*) lpv;
    if (NULL != server_t)
    {

        for (;;)
        {
            socket_fd client;
            u32 client_len;
            sockaddr addr;
            thread_t th = { .func = thread_per_client };
            mcf_error("server_id=%d",server_t->sock_fd);
            client = accept(server_t->sock_fd, &addr, &client_len);
            mcf_error("here %d",client);
            if (client!=SOCKET_ERROR)
            {
                client_t *clt=(client_t *)malloc(sizeof(client_t));
                clt->client=client;
                clt->addr=addr;
                th.params = clt;
                begin_thread(&th);
            }

        }
    }
    if(server_t)free(server_t);
//    ResetEvent(event);
    return 0;
}
void
test_thread()
{
    thread_t th = { .func = thread_func };
    begin_thread(&th);
}

void
test_net()
{
    socket_t *sock;
    thread_t thread_serv;
    sock=(socket_t*)malloc(sizeof(socket_t));
    sock->addr = NULL;
    sock->back_log = 1024;
    sock->port = 8088;
    sock->protocl = PROTO_TCP;
    sock->type = TCP;
    thread_serv.func = server;
    if (-1 == service_server(sock))
    {
        mcf_error("test_net error");
    }

    thread_serv.params = sock;
//    mcf_error("%d",sock->sock_fd);
    if (0==begin_thread(&thread_serv))
    {
        mcf_error("thread_serv");
    }
//   Sleep(10);
}

void
test_all()
{

//    test_thread();
    test_net();
    while(1)
    Sleep(10000);
//    event=CreateEventA(NULL,0,0,"exit");
//    WaitForSingleObject(event,INFINITE);
}

#endif /* TESTS_C_ */
